import config from '../../package.json'
import Cookies from 'vue-cookies'

export class ServiceProxyConfig {
  public static readonly acceptLanguageKey = 'acceptLanguage'
  public static readonly accessTokenKey = 'accessToken'
  /**
   * Returns a valid value for the Authorization header.
   * Used to dynamically inject the current auth header.
   */
  public getAuthorization(): string {
    const cookies: any = Cookies
    const accessToken = cookies.get(ServiceProxyConfig.accessTokenKey)
    return accessToken || ''
  }

  public getAcceptLanguage(): string {
    const cookies: any = Cookies
    const acceptLanguage = cookies.get(ServiceProxyConfig.acceptLanguageKey)
    return acceptLanguage || 'zh-Hans'
  }
}

export abstract class AbpServiceBase {
  protected readonly config: ServiceProxyConfig

  protected constructor(config: ServiceProxyConfig) {
    this.config = config
  }

  /**
   * 处理请求
   * @param options 请求
   * @returns 请求
   */
  protected transformOptions(options: RequestInit): Promise<RequestInit> {
    options.headers = {
      ...options.headers,
      Authorization: this.config.getAuthorization(),
      'accept-language': this.config.getAcceptLanguage() || '',
    }

    // 设置跨域请求发送cookie
    options.credentials = 'include'
    // 指示请求将使用CORS
    options.mode = 'cors'
    options.cache = 'default'
    console.log('transformOptions', 'options:', options)
    return Promise.resolve(options)
  }

  protected transformResult(
    url: string,
    response: Response,
    processor: (response: Response) => Promise<any>,
  ): Promise<any> {
    console.log('transformResult', 'url:', url, response)
    if (response === null) return Promise.resolve()
    const contentType = response.headers.get('content-type')
    if (contentType != null && contentType.indexOf('text/plain') >= 0) {
      return response.text()
    }

    return processor(response)
  }

  getBaseUrl(defaultUrl: string, baseUrl?: string): string {
    return config.application.apis.default.url
  }

  getClientUrl(defaultUrl: string, clientUrl?: string): string {
    return config.application.clientUrl
  }
}
